<script setup lang="ts">
import { ref, onMounted, nextTick, computed, onUnmounted } from 'vue'
import { getConsoleData, type ConsoleData } from '@/api/admin'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 仪表盘数据
const dashboardData = ref<ConsoleData | null>(null)
const loading = ref(true)

// ECharts实例引用
let rehabChart: echarts.ECharts | null = null
let registerChart: echarts.ECharts | null = null
let assessmentChart: echarts.ECharts | null = null
const rehabChartRef = ref<HTMLElement>()
const registerChartRef = ref<HTMLElement>()
const assessmentChartRef = ref<HTMLElement>()

// 统计数据卡片
const statsData = computed(() => {
  if (!dashboardData.value) return []
  return [
    {
      title: '学生总数',
      value: dashboardData.value.studentCount,
      color: '#409eff',
    },
    {
      title: '教师总数',
      value: dashboardData.value.teacherCount,
      color: '#67c23a',
    },
    {
      title: '管理员总数',
      value: dashboardData.value.adminCount,
      color: '#e6a23c',
    },
    {
      title: '待审核用户',
      value: dashboardData.value.pendingCount,
      color: '#f56c6c',
    },
  ]
})

// 获取控制台数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    const res = await getConsoleData()
    dashboardData.value = res.data
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    console.error('获取控制台数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化所有图表
const initCharts = () => {
  renderRehabChart()
  renderRegisterChart()
  renderAssessmentChart()

  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => {
    rehabChart?.resize()
    registerChart?.resize()
    assessmentChart?.resize()
  })
}

// 渲染康复计划趋势图表
const renderRehabChart = () => {
  if (!rehabChartRef.value || !dashboardData.value) return

  // 如果已经初始化过，则销毁重建
  if (rehabChart) {
    rehabChart.dispose()
  }

  rehabChart = echarts.init(rehabChartRef.value)
  const trend = dashboardData.value.rehabPlanTrend
  const completeTrend = dashboardData.value.rehabPlanCompleteTrend

  rehabChart.setOption({
    title: {
      text: '康复计划趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['创建计划数', '完成计划数'],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: trend.map((i) => formatDateLabel(i.date)),
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '创建计划数',
        type: 'bar',
        data: trend.map((i) => Number(i.count)),
        color: '#409eff',
      },
      {
        name: '完成计划数',
        type: 'bar',
        data: completeTrend.map((i) => Number(i.count)),
        color: '#67c23a',
      },
    ],
  })
}

// 渲染用户注册趋势图表
const renderRegisterChart = () => {
  if (!registerChartRef.value || !dashboardData.value) return

  // 如果已经初始化过，则销毁重建
  if (registerChart) {
    registerChart.dispose()
  }

  registerChart = echarts.init(registerChartRef.value)
  const trend = dashboardData.value.userRegisterTrend

  registerChart.setOption({
    title: {
      text: '用户注册趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: trend.map((i) => formatDateLabel(i.date)),
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '注册用户数',
        type: 'line',
        data: trend.map((i) => Number(i.count)),
        smooth: true,
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#e6a23c',
        },
        lineStyle: {
          width: 3,
          color: '#e6a23c',
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.5)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0.1)' },
          ]),
        },
      },
    ],
  })
}

// 渲染评估趋势图表
const renderAssessmentChart = () => {
  if (!assessmentChartRef.value || !dashboardData.value) return

  // 如果已经初始化过，则销毁重建
  if (assessmentChart) {
    assessmentChart.dispose()
  }

  assessmentChart = echarts.init(assessmentChartRef.value)
  const onlineTrend = dashboardData.value.onlineAssessmentTrend
  const offlineTrend = dashboardData.value.offlineAssessmentTrend

  assessmentChart.setOption({
    title: {
      text: '评估记录趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: ['线上评估', '线下评估'],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: onlineTrend.map((i) => formatDateLabel(i.date)),
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '线上评估',
        type: 'line',
        stack: 'Total',
        data: onlineTrend.map((i) => Number(i.count)),
        color: '#f56c6c',
      },
      {
        name: '线下评估',
        type: 'line',
        stack: 'Total',
        data: offlineTrend.map((i) => Number(i.count)),
        color: '#909399',
      },
    ],
  })
}

// 格式化日期标签
const formatDateLabel = (dateStr: string): string => {
  return dateStr.substring(5) // 只显示月-日部分
}

// 初始化
onMounted(() => {
  fetchDashboardData()

  // 如果用户信息未加载，尝试加载
  if (!userStore.isLoggedIn) {
    userStore.init()
  }
})

// 清理资源
onUnmounted(() => {
  if (rehabChart) {
    rehabChart.dispose()
    rehabChart = null
  }
  if (registerChart) {
    registerChart.dispose()
    registerChart = null
  }
  if (assessmentChart) {
    assessmentChart.dispose()
    assessmentChart = null
  }

  window.removeEventListener('resize', () => {
    rehabChart?.resize()
    registerChart?.resize()
    assessmentChart?.resize()
  })
})

// 快捷操作按钮事件
const handleAddStudent = () => {
  const userRole = userStore.role
  if (userRole === '管理员' || userRole === '超级管理员') {
    router.push({ name: 'userManager', query: { action: 'add' } })
  } else {
    router.push({ name: 'studentManager', query: { action: 'add' } })
  }
}

const handleAddTeacher = () => {
  // 角色检查：只有管理员和超级管理员可以添加教师
  const userRole = userStore.role
  if (userRole === '管理员' || userRole === '超级管理员') {
    router.push({ name: 'userManager', query: { action: 'add' } })
  } else {
    ElMessage.error('您没有添加教师的权限，只有管理员才能执行此操作')
  }
}

const handleCreatePlan = () => {
  router.push({ name: 'offlineEvaluation' })
}

const handleAddEvaluation = () => {
  router.push({ name: 'offlineEvaluation', query: { action: 'addEvaluation' } })
}
</script>

<template>
  <div class="home-container">
    <div class="page-header">
      <h1 class="page-title">控制台</h1>
      <div class="welcome-message">
        欢迎回来，{{
          new Date().getHours() < 12 ? '上午好' : new Date().getHours() < 18 ? '下午好' : '晚上好'
        }}
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col
        :xs="24"
        :sm="12"
        :md="6"
        v-for="(stat, index) in statsData"
        :key="index"
        class="stats-col"
      >
        <el-card
          shadow="hover"
          class="stats-card"
          :style="{ borderTop: `4px solid ${stat.color}` }"
        >
          <div class="stats-title">{{ stat.title }}</div>
          <div class="stats-value">{{ stat.value }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 1 - 左右布局 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="rehabChartRef" style="height: 350px; width: 100%"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="registerChartRef" style="height: 350px; width: 100%"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 2 - 一行 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div ref="assessmentChartRef" style="height: 350px; width: 100%"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户统计摘要 -->
    <el-row :gutter="20" class="summary-row" v-if="dashboardData">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="summary-card">
          <template #header>
            <div class="card-header">
              <span>用户统计</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="总用户数">
              {{ dashboardData.totalUsers }}
            </el-descriptions-item>
            <el-descriptions-item label="今日新增">
              {{ dashboardData.todayNewUsers }}
            </el-descriptions-item>
            <el-descriptions-item label="学生用户">
              {{ dashboardData.studentCount }}
            </el-descriptions-item>
            <el-descriptions-item label="教师用户">
              {{ dashboardData.teacherCount }}
            </el-descriptions-item>
            <el-descriptions-item label="管理员">
              {{ dashboardData.adminCount }}
            </el-descriptions-item>
            <el-descriptions-item label="待审核">
              {{ dashboardData.pendingCount }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card shadow="hover" class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" icon="Plus" @click="handleAddStudent">添加学生</el-button>
            <el-button type="success" icon="Plus" @click="handleAddTeacher">添加教师</el-button>
            <el-button type="warning" icon="Document" @click="handleCreatePlan"
              >创建康复计划</el-button
            >
            <el-button type="info" icon="DocumentChecked" @click="handleAddEvaluation"
              >添加评估记录</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.home-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.welcome-message {
  font-size: 14px;
  color: #606266;
}

.stats-row {
  margin-bottom: 20px;
  width: 100%;
}

.stats-col {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
}

.stats-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 16px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
  width: 100%;
}

.chart-card {
  margin-bottom: 20px;
}

.summary-row {
  margin-bottom: 20px;
}

.summary-card,
.quick-actions-card {
  height: 100%;
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: space-around;
  padding: 10px 0;
}

.quick-actions .el-button {
  margin-bottom: 10px;
  min-width: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card {
  border-radius: 4px;
  border: none;
  transition: all 0.3s;
  width: 100%;
}

.el-card:hover {
  box-shadow:
    0 6px 16px -8px rgba(0, 0, 0, 0.1),
    0 9px 28px 0 rgba(0, 0, 0, 0.05),
    0 12px 48px 16px rgba(0, 0, 0, 0.03);
}

:deep(.el-descriptions__label) {
  width: 90px;
}
</style>
